package com.wee.aircoach_user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigtotoro.util.SharedPreferencesUtil;
import com.bigtotoro.widgets.AppProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wee.entity.MD5Util;
import com.wee.entity.Plan_post;
import com.wee.entity.ShareWithPlan;
import com.wee.entity.Sharedata;
import com.wee.entity.User_detail;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by Solomon on 2015/12/31.
 */
public class PlayendActivity extends Activity implements View.OnClickListener{
    private ImageView left,mid,right;
    private TextView name,jihua,num,sum;
    private Button ff,ss;
    String level;
    User_detail data;
    int it,planid,exact;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticity_play_end);
        exact=  SharedPreferencesUtil.getInt(this, com.wee.aircoach_user.Constant.USERTIME);
      initView();
       gethttp();
    }
    private void gethttp() {
        String  user_main=Constant.USER_DETAIL+ MD5Util.md5(exact)+"&id="+it+ "&ver" + new Random().nextInt(9999);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, user_main,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {

                        String str = responseInfo.result;
                        Gson gs = new Gson();
                        JsonObject jo = gs.fromJson(str, JsonObject.class);
                        JsonElement je = jo.get("status");
                        String status = je.getAsString();
                        if ("ok".equals(status)) {
                            JsonObject object = jo.getAsJsonObject("data");
                            try {
                                data = gs.fromJson(object, User_detail.class);
                                name.setText(data.getCoach().getName() + "");
                                jihua.setText(data.getPlan().getName() + "");
                                num.setText((data.getComplete() + 1) + "");
                                sum.setText(data.getPlan_count().toString());
                                planid = data.getPlan().getId();
                            } catch (Exception r) {
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        System.out.println(e.getMessage());
                    }
                });
    }

    private void initView() {
        ImageView imageView = (ImageView)findViewById(R.id.bg_iv);
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("drawable://" + R.drawable.tarin_finish, imageView);
        ss=(Button)findViewById(R.id.share);
        ss.setOnClickListener(this);
        ff=(Button)findViewById(R.id.fanhui);
        ff.setOnClickListener(this);
        jihua= (TextView) findViewById(R.id.jihua);
        num= (TextView) findViewById(R.id.num);
        sum= (TextView) findViewById(R.id.sum);
         name= (TextView) findViewById(R.id.coach_nz);
        left= (ImageView) findViewById(R.id.left);
        left.setOnClickListener(this);
         mid= (ImageView) findViewById(R.id.mid);
         mid.setOnClickListener(this);
         right= (ImageView) findViewById(R.id.right);
         right.setOnClickListener(this);
        it=SharedPreferencesUtil.getInt(PlayendActivity.this, Constant.USERID);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left:
                left.setBackgroundResource(R.drawable.easy_no);
                mid.setClickable(false);
                right.setClickable(false);
                mid.setBackgroundResource(R.drawable.mid);
                right.setBackgroundResource(R.drawable.nan);
                level="easy";
                break;
            case R.id.mid:
                left.setClickable(false);
                right.setClickable(false);
                left.setBackgroundResource(R.drawable.easy);
                mid.setBackgroundResource(R.drawable.mid_on);
                right.setBackgroundResource(R.drawable.nan);
                level="kind";

                break;
            case R.id.right:
                mid.setClickable(false);
                left.setClickable(false);
                left.setBackgroundResource(R.drawable.easy);
                mid.setBackgroundResource(R.drawable.mid);
                right.setBackgroundResource(R.drawable.nan_on);
                level="trouble";
                break;
            case  R.id.share:
                shareWith();
                break;
            case R.id.fanhui:
                try{
                    if(level.equals("easy")){
                        post_json("easy");
                    }else if(level.equals("trouble")){
                        post_json("trouble");
                    }
                }catch (Exception r){
                    post_json("kind");
                }
                //百分之的进度条
            /*   int aa= SharedPreferencesUtil.getInt(PlayendActivity.this, Constant.NUM);
                int mm=aa+1;
                SharedPreferencesUtil.setInt(PlayendActivity.this,Constant.NUM,mm);*/
                startActivity(new Intent(PlayendActivity.this, MainActivity.class));
                finish();
            break;
        }
    }

    //分享
    private void shareWith(){
        String  old=num.getText().toString().trim();
        String  have=sum.getText().toString().trim();
        ShareWithPlan content = new ShareWithPlan();
        content.setPlan_id(planid + "");
        content.setComplete(old);
        content.setPlan_count(have);
        Gson gson = new Gson();
        String json = gson.toJson(content);

        RequestParams params = new RequestParams();
        AppProgressBar.checkAndCreateProgressBar(this);
        params.addBodyParameter("userId", ""+it);
        params.addBodyParameter("token", ""+ MD5Util.md5(exact));
        params.addBodyParameter("type", "plan");
        params.addBodyParameter("content", json);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                //改动借口
                Constant.USER_SHARE,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                            String str = responseInfo.result;
                            Gson gs=new Gson();
                            JsonObject jo=gs.fromJson(str, JsonObject.class);
                            JsonElement je=jo.get("status");
                            String status = je.getAsString();
                            if("ok".equals(status)){
                                JsonObject object = jo.getAsJsonObject("data");
                                Sharedata list1 =gs.fromJson(object, Sharedata.class);
                                share(list1.getUrl());
                                AppProgressBar.closeProgressBar();
                            }
                            AppProgressBar.closeProgressBar();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        AppProgressBar.closeProgressBar();
                    }
                });



    }
//shareSdk
    private void share(String  url) {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(data.getCoach().getName()+"教练 为我量身定制了计划："+data.getPlan().getName()+"，练完巨酸爽！");
        oks.setUrl(url);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("光合教练—真人教练在线定制健身服务");

        //     oks.setTitleUrl("http://www.mob.com");
        oks.setImageUrl("http://image-test.aircoach.cn/media/340ef818fafa831ee270dadac0f0e39a.png");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
    /*    // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");*/

// 启动分享GUI
        oks.show(this);

    }

    private void post_json(String  ee) {
        RequestParams params = new RequestParams();
        Plan_post content = new Plan_post();
        content.setId(data.getPlan().getId() + "");
         String  count =num.getText().toString().trim();
         String all=sum.getText().toString().trim();
        content.setCount(count+"/"+all);
        content.setFeedback(""+ee);
        Gson gson = new Gson();
        String json = gson.toJson(content);
        params.addBodyParameter("userId", it+"");
        params.addBodyParameter("token", "" + MD5Util.md5(exact));
        params.addBodyParameter("content", json);
        params.addBodyParameter("type", "plan");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                Constant .TICE_HISTORY,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;
                        JSONObject json;

                        try {
                            json = new JSONObject(str);
                            if(json.getString("status").equals("ok")){
                                int userid = json.getInt("data");
                         //       Toast.makeText(PlayendActivity.this,"记录成功",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });
    }



}
